package com.maoning.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.maoning.common.to.es.SkuEsModel;
import com.maoning.gulimallsearch.constant.EsConstant;
import com.maoning.gulimallsearch.config.GulimallESConfig;
import com.maoning.gulimallsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : 猫宁
 * @Date: 2021/12/7
 */
@Slf4j
@Service("ProductSaveServiceImpl")
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
//        保存数据到es的步骤
//        1.建立索引,kibana已经弄好了
//        2.给es中保存这些数据,多的话使用bulk批量保存
        final BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            final IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            final String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString,XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        final BulkResponse bulkResponse = client.bulk(bulkRequest, GulimallESConfig.COMMON_OPTIONS);
        final boolean b = bulkResponse.hasFailures();
        if(b){
            final List<String> list = Arrays.stream(bulkResponse.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品上架错误,错误id:{}",list);
        }
        return !b;
    }
}
